<template>
  <div class="printLabelPage">
    <div class="row controlBar items-center justify-between">
      <div class="col">
        <q-input
          standout
          v-model="searchWO"
          placeholder="选取发镶单单号"
          bg-color="white"
          :input-style="{ color: 'black' }"
          dense
          @keyup.enter="addPrintLabel(searchWO)"
        >
          <q-icon
            name="fa-solid fa-magnifying-glass"
            class="searchSVG"
            @click="addPrintLabel(searchWO)"
          />
        </q-input>
      </div>
      <div calss="col-auto">
        <form ref="fileForm">
          <input
            type="file"
            ref="woFiles"
            style="display: none"
            @change="getWOList()"
            accept=".csv"
          />
        </form>
        <q-btn push color="blue-10" class="uploadBtn" @click="uploadWOList()">
          <q-icon name="fa-solid fa-arrow-up-from-bracket" class="uploadSVG" />
        </q-btn>
      </div>
      <div class="col">
        <div class="q-gutter-md">
          <q-select
            filled
            dense
            v-model="printerNo"
            bg-color="white"
            :options="printers"
            label="选择打印机"
          />
        </div>
      </div>
      <div calss="col-auto">
        <q-btn
          push
          color="warning"
          class="printBtn"
          label="打印"
          @click="printLabel()"
        >
          <q-icon name="fa-solid fa-print" class="printSVG" />
        </q-btn>
      </div>
    </div>
    <div class="orderTableBox">
      <q-table
        class="orderTable"
        flat
        bordered
        table-header-class="bg-indigo-2"
        :rows="otrows"
        :columns="otcolumns"
        row-key="orderNo"
      >
        <template v-slot:body-cell-serialNo="props">
          <q-td :props="props">
            {{ props.rowIndex + 1 }}
          </q-td>
        </template>

        <!-- 
              <template v-slot:body-cell-printDate="props">
                  <q-td key="printDate" :props="props">
                    <span v-show="props.row.goldPrintDate">金仓: {{ props.row.goldPrintDate }}</span> <br v-if="props.row.goldPrintDate"/>
                    <span v-show="props.row.stonePrintDate">石仓: {{ props.row.stonePrintDate }}</span>
                  </q-td>
              </template>
              -->
        <template v-slot:body-cell-remove="props">
          <q-td :props="props">
            <q-icon
              name="fa-solid fa-trash"
              class="removeSVG"
              @click="removePrintLabel(props.rowIndex)"
            />
          </q-td>
        </template>
      </q-table>
    </div>
  </div>
</template>

<script setup>
import { ref, toRaw } from "vue";
import { useQuasar } from "quasar";
import { usePrintLabelStore } from "src/stores/modules/printLabelStore";
import { useUserStore } from "src/stores/modules/userStore";

const $q = useQuasar();
const userStore = useUserStore();
const printLabelStore = usePrintLabelStore();

// Get Role
const accID = userStore.currentDept.accID;

const searchWO = ref("");
const fileForm = ref(null);
const woFiles = ref(null);
const printers = ref([]);
const printerNo = ref(null);
let originalTb = [];

// WO Table
const otcolumns = [
  {
    name: "serialNo",
    align: "center",
    label: "序号",
    field: "serialNo",
    sortable: false,
  },
  {
    name: "orderNo",
    required: true,
    label: "发镶单单号",
    align: "center",
    field: (row) => row.orderNo,
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "source",
    align: "center",
    label: "地点",
    field: "source",
    sortable: true,
  },
  {
    name: "designNum",
    align: "center",
    label: "设计编号",
    field: "designNum",
    sortable: true,
  },
  {
    name: "goldType",
    align: "center",
    label: "成色",
    field: "goldType",
    sortable: true,
  },
  {
    name: "orderQty",
    align: "center",
    label: "件数",
    field: "qty",
    sortable: true,
  },
  {
    name: "printStatus",
    align: "center",
    label: "金仓打印狀態",
    field: "goldPrintDate",
    sortable: true,
  },
  {
    name: "printDate",
    align: "center",
    label: "石仓打印狀態",
    field: "stonePrintDate",
    sortable: true,
  },
  {
    name: "remove",
    align: "center",
    label: "移除",
    field: "remove",
    sortable: false,
  },
];

let otrows = ref([]);

// Function: Get Printer Info
const getPrinterInfo = async () => {
  const res = await printLabelStore.getPrinterInfo(accID);
  console.log("response: ", res);
  if (res) {
    const defaultPrinter = printLabelStore.getDefaultPrinter;
    printerNo.value = defaultPrinter;
    const printerChoices = printLabelStore.getPrinterChoices;
    printers.value = printerChoices;
    console.log("default printer");
    console.log(printers.value);
  } else {
    // show error
    console.log("failed to get printerInfo");
  }
};
getPrinterInfo();

// Function: Check if new added already included in the woList
const checkWOList = (newRows) => {
  let otrowsCopy = [...JSON.parse(JSON.stringify(otrows.value))];

  const removedWOList = otrowsCopy.filter(
    (wo) => !newRows.some((e) => e.orderNo === wo.orderNo)
  );
  otrows.value = removedWOList;
};

// Function: Upload work order list -> trigger getWOList
const uploadWOList = () => {
  woFiles.value.click();
};

// Function: Get work order list (read csv file)
const getWOList = async () => {
  const files = woFiles.value.files[0];

  if (files !== undefined) {
    const formData = new FormData();
    formData.append("accID", accID);
    formData.append("orderNo", null);
    formData.append("file", files);

    // call api
    const res = await printLabelStore.searchPrintLabel(formData);
    console.log("response: ", res);

    if (res) {
      let newRows = [];
      originalTb = toRaw(printLabelStore.getWOList);
      newRows = [...JSON.parse(JSON.stringify(originalTb))];
      checkWOList(newRows);
      otrows.value = otrows.value.concat(newRows);
    } else {
      // console.log('failed to get woList')
      $q.notify({
        type: "negative",
        textColor: "white",
        message: "错误发生 !",
        timeout: 2000,
        position: "center",
      });
    }
  }

  fileForm.value.reset();
};

// Function: Add new print label (by searching orderNo)
const addPrintLabel = async (orderNo) => {
  // console.log('add new label: ', orderNo)

  if (orderNo) {
    // Check if already exist
    if (otrows.value.find((wo) => wo.orderNo === orderNo)) {
      $q.notify({
        type: "warning",
        textColor: "white",
        message: "工单已经存在 !",
        timeout: 2000,
        position: "center",
      });
    } else {
      // call api
      const formData = new FormData();
      formData.append("accID", accID);
      formData.append("orderNo", orderNo);
      formData.append("file", null);

      const res = await printLabelStore.searchPrintLabel(formData);
      console.log("response: ", res);

      if (res) {
        let newRows = [];
        originalTb = toRaw(printLabelStore.getWOList);
        newRows = [...JSON.parse(JSON.stringify(originalTb))];
        checkWOList(newRows);
        otrows.value = otrows.value.concat(newRows);
      } else {
        // console.log('failed to get woList')
        $q.notify({
          type: "negative",
          textColor: "white",
          message: "错误发生 !",
          timeout: 2000,
          position: "center",
        });
      }
    }
  }

  searchWO.value = "";
};

// Function: Remove seleceted print label
const removePrintLabel = (rowIndex) => {
  otrows.value = [
    ...otrows.value.slice(0, rowIndex),
    ...otrows.value.slice(rowIndex + 1),
  ];
};

// TO-DO: Function: Print Labels
const printLabel = async () => {
  const selectedPrinter = printerNo.value.value;
  const printLabelList = otrows.value.map((wo) => wo.orderNo);
  console.log('selectedPrinter', selectedPrinter);
  if (
    printerNo.value === null ||
    printerNo.value === undefined ||
    printerNo.value === ""
  ) {
    $q.notify({
      type: "warning",
      textColor: "white",
      message: "请先选择打印机",
      timeout: 2000,
      position: "center",
    });
  } else {
    // call api
    console.log("call printLabel api for accID: ", accID);
    const res = await printLabelStore.printLabel(
      selectedPrinter,
      printLabelList,
      accID
    );
    console.log("response: ", res);
    const printDate = toRaw(printLabelStore.getPrintDate);
    console.log("printDate: ", printDate);
    const selectedPrinterObj = printers.value.find(i=>i.value==selectedPrinter)
    // console.log("selectedPrinterObj",selectedPrinterObj.label.split('-')[0]);
    if (selectedPrinterObj.label.split('-')[0] === "金仓") {
      otrows.value.forEach((row) => {
        row.goldPrintDate = printDate;
      });
    } else {
      otrows.value.forEach((row) => {
        row.stonePrintDate = printDate;
      });
    }

    if (res.status) {
      // show success
      // get result date
      // update print status
      
      if (res.message) {
        $q.notify({
          type: "positive",
          textColor: "",
          message: res.message,
          timeout: 2000,
          position: "center",
        });
      }
      
    } else {
      // show error
      console.log("failed to get woList");
      if (res.message) {
        $q.notify({
          type: "negative",
          message: res.message,
          timeout: 2000,
          position: "center",
        });
      }else{
        $q.notify({
          type: "negative",
          textColor: "white",
          message: "错误发生 !",
          timeout: 2000,
          position: "center",
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.printLabelPage {
  width: 100%;
  @media (max-width: 480px) {
    font-size: 1.5em;
  }
  .controlBar {
    background-color: #9eabea;
    padding: 10px 10px 10px 10px;
    width: 100%;
    div {
      margin-right: 5px;
    }
    .searchSVG {
      margin-top: auto;
      margin-bottom: auto;
      color: black;
      float: right;
    }
    .printBtn {
      font-size: 1rem;
      .printSVG {
        margin-left: 5px;
      }
    }

    .uploadBtn {
      font-size: 1rem;
      // .uploadSVG
    }
  }

  .orderTableBox {
    margin-top: 20px;
    background-color: rgba(255, 255, 255, 0.849);
    width: 95%;
    margin-left: auto;
    margin-right: auto;
    padding: 10px 10px 10px 10px;
    border-radius: 10px;
  }
}
</style>
